<template>
    <div>
        <van-overlay :show="showPage" type="primary"/>
        <titleVue @close="close" :title="title_text"></titleVue>
        <div class="tagPage2">
            <div class="policy">
                <div class="content">
                    <van-form @submit="onSubmit" validate-first>
                        <!--    物品名称-->
                        <div class="box">
                            <div class="title">
                                <span>* </span><b>物品名称</b>
                            </div>
                            <van-field
                                class="input description"
                                v-model="nameVal"
                                rows="1"
                                autosize
                                type="textarea"
                                style="max-height: 5rem; overflow: auto;"
                                placeholder="请输入物品名称"
                            />
                        </div>

                        <!--    物品介绍-->
                        <div class="box">
                            <div class="title">
                                <span>* </span><b>物品介绍</b>
                            </div>
                            <div class="picker description">
                                <van-field
                                    class="input"
                                    v-model="p_description"
                                    rows="4"
                                    autosize
                                    type="textarea"
                                    style="max-height: 10rem; overflow: auto;"
                                    placeholder="请介绍宝贝品牌型号、入手渠道、新旧程度等"
                                />
                            </div>
                        </div>

                        <!--    物品照片-->
                        <div class="box">
                            <div class="title">
                                <span>* </span><b style="margin: -0.1rem 0 0.2rem 0">物品照片</b>
                            </div>
                            <div class="picker">
                                <van-field name="uploader" style="padding: 0">
                                    <template #input>
                                        <van-uploader
                                            v-if="is_update"
                                            :max-count="5"
                                            preview-size="3.5rem"
                                            v-model="uploader"
                                            accept="image/*"
                                            multiple/>
                                        <van-uploader
                                            v-else
                                            accept="image/*"
                                            :max-count="5"
                                            preview-size="3.5rem"
                                            v-model="uploader"
                                        />
                                    </template>
                                </van-field>
                            </div>
                        </div>
                        <!--    联系方式-->
                        <div class="box">
                            <div class="title">
                                <span>* </span><b>联系方式</b>
                            </div>
                            <div class="picker">
                                <van-field
                                    class="input"
                                    type="tel"
                                    v-model="phone_type"
                                    placeholder="请留下您的手机号码，以便买家联系到您"
                                />
                            </div>
                        </div>

                        <!--    底部提交按钮-->
                        <div class="submit" style="margin-top: 14rem">
                            <div class="left">
                                <van-checkbox
                                    shape="square">
                                </van-checkbox>
                                <span>
                        请认真阅读并遵守<a href="javascript:void(0)">《隐私政策及免费声明》</a>
                </span>
                            </div>
                            <div class="right">
                                <button v-if="is_update" native-type="submit">修改提交</button>
                                <button v-else native-type="submit">提交</button>
                            </div>
                        </div>
                    </van-form>
                </div>
            </div>

        </div>
        <div>
            <BottomMenu></BottomMenu>
        </div>
    </div>

</template>

<script>
import titleVue from "../ghhz/title.vue";
import BottomMenu from "../ghhz/bottomMenu.vue";
import {Dialog, Toast} from 'vant'
import axios from 'axios'
export default {
    name: "TagPage2",
    components: {
        titleVue,
        BottomMenu
    },
    data() {
        return {
            title_text: "测试",
            nameVal: '',        // 物品名称 临时值
            p_type_val: '',     // 物品类型 临时值
            jy_type_val: '',    // 交易类型 临时值
            area_val: '',        // 所在区域 临时值
            p_description: '',  // 物品介绍
            remark: '', // 物品交换意向
            uploader: [],       // 物品照片
            phone_type: '',     // 联系方式
            showPage: false, // 是否显示遮罩层
            selectedPType: [], // 保存选择的数据
            activeIndexList: [],
            result: [],
            produc_imgs: [], // 商品图片key
            delete_imgs: [], // 删除的图片key
            no_delete_imgs: [], // 不需要删除的图片key
            imgFile: [], // 新上传的图片
            is_update: false,
            phone: localStorage.getItem('phone')
        }
    },
    inject: ['$apiUrl', '$headImgUrl'],
    methods: {
        // 返回布尔值
        beforeRead(file) {
            console.log(file.type, '111111111111111111111111111')
            this.transferFormat(file)
            // if (file.type !== 'image/jpeg') {
            //     // Toast('请上传 jpg 格式图片');
            //     // return false;
            // }
            return true;
        },
        // 转图片格式
        transferFormat(file) {
            // 创建 FileReader 对象
            const reader = new FileReader();
            debugger
            // 读取文件完成时触发
            reader.onload = function(e) {
                // 创建一个新的图片元素
                const img = new Image();
                // 图片加载完成时触发
                img.onload = function() {
                    // 创建一个 Canvas 元素
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    // 设置 Canvas 的尺寸和图片尺寸相同
                    canvas.width = img.width;
                    canvas.height = img.height;
                    // 在 Canvas 上绘制图片
                    ctx.drawImage(img, 0, 0);

                    // 将 Canvas 内容转换为 PNG 格式的 Base64 数据
                    const pngData = canvas.toDataURL('image/png');

                    // 在这里可以将 pngData 发送给服务器或进行其他操作
                    console.log(pngData,'222222222');
                };

                // 将文件内容设置为图片的源
                img.src = e.target.result;
            };

            // 读取文件内容
            reader.readAsDataURL(file);

        },
        close() {// 关闭当前窗口
            this.va.close();
        },
        // 点击提交按钮
        onSubmit() {
            Dialog.confirm({
                title: '是否提交',
                message: `<span>是否将<span style="color: #f79305">${this.nameVal}信息发布到信息广场？</span></span>`,
                cancelButtonText: '继续编辑',
                allowHtml: true,
                confirmButtonText: '发布',
                confirmButtonColor: '#f79305'
            })
                .then(() => {
                    // on confirm
                    console.log('提交')
                    // 修改
                    if (this.is_update) {
                        // 新增
                        this.update();
                    } else {
                        this.save();
                    }
                })
                .catch(() => {
                    // on cancel
                    console.log('继续编辑2222')
                });
        },
        save() {
            this.showPage = true;
            console.log('保存数据')
            const formData = new FormData()
            formData.append('name', this.nameVal)
            formData.append('description', this.p_description)
            formData.append('phone_type', this.phone_type)
            formData.append('phone', this.phone)
            this.uploader.forEach(img => {
                formData.append('imgs', img.file)
            })
            console.log(formData)
            Toast.loading({
                duration: 0, // 持续展示 toast
                message: '发布中...',
                forbidClick: true,
            });
            console.log('发送请求')
            // 定义标志变量
            const url = this.$apiUrl + '/product/saveProduct';
            this.$http.post(url, formData,{
                headers: {
                    'Content-type': 'multipart/form-data'
                }
            })
                .then((result) => {
                    console.log(result)
                    if (result.data.code == 1) {
                        console.log(result)
                        this.showPage = false;
                        this.$message.success("发布成功");
                        this.$router.push('/AppHome/Home')
                    } else {
                        this.$message.error("发布失败，请重新发布");
                        console.log(result)
                    }
                })
                .catch((error) => {
                    console.log(error);
                    this.showPage = false;
                    this.$message.error("商品发布失败!!!");
                })
                .finally(() => {
                    Toast.clear(); // 关闭 loading
                });
        },
        update() {
            this.showPage = true;
            // 过滤出不需要删除的图片
            this.no_delete_img = this.uploader.filter(item => item.index != undefined)
            // 过滤出新上传的图片
            this.imgFile = this.uploader.filter(item => item.index == undefined)
            // 过滤出已经删除的图片key
            let len = this.produc_imgs.length
            let noLen = this.no_delete_img.length;
            console.log(len)
            // 判断是否存在不需要删除的图片 有则过滤出来
            if (noLen > 0) {
                for (let i = 0, j = 0; i < len; i++) {
                    if (this.no_delete_img[j].index !== i) {
                        this.delete_imgs.push(this.produc_imgs[i])
                    } else {
                        if (j < noLen - 1) {
                            j++;
                        }
                    }
                }
                // 截取出不需要删除的图片key
                for (let i = 0; i < noLen; i++) {
                    this.no_delete_img[i] = this.no_delete_img[i].url.replace('web/file/download?key=', '')
                }
            } else if (this.imgFile.length > 0 && noLen === 0) {
                for (let i = 0; i < len; i++) {
                    this.delete_imgs.push(this.produc_imgs[i])
                }
            }
            console.log('保存修改后的数据')
            const formData = new FormData()
            formData.append('proId', this.proId)
            formData.append('name', this.nameVal)
            formData.append('description', this.p_description)
            formData.append('phone', this.phone_type)
            formData.append('deleteImgs', this.delete_imgs)
            formData.append('noDeleteImg', this.no_delete_img)
            formData.append('createTime', this.createTime)
            formData.append('remark', this.remark)
            formData.append('phone', this.phone)
            this.imgFile.forEach(img => {
                formData.append('imgs', img.file)
            })
            Toast.loading({
                duration: 0, // 持续展示 toast
                message: '发布中...',
                forbidClick: true
            });
            // 定义标志变量
            var flag = false;
            this.axios.post("app/pro/updateProduct", formData, {
                headers: {
                    'Content-type': 'multipart/form-data'
                }
            })
                .then((result) => {
                    flag = true; // 请求完成
                    if (result.data.code == 1) {
                        console.log(result)
                        this.showPage = false;
                        this.$message.success("发布成功");
                        this.$router.push('/app/releaseSuccess')
                    } else {
                        console.log(result)
                        this.showPage = false;
                        this.$message.error("发布失败，请重新发布");

                    }
                })
                .catch((error) => {
                    console.log(error);
                    flag = true; // 请求完成
                    this.showPage = false;
                    this.$message.error("商品发布失败!!!");
                })
                .finally(() => {
                    if (flag) {
                        Toast.clear(); // 关闭 loading
                    }
                });
        },
    }
}
</script>

<style lang="less" scoped>

.tagPage2 {
    overflow: hidden;

    .policy {
        overflow: auto;
        height: calc(100vh - 2.75rem);
        // 表单内容
        .content {
            padding: 1rem;

            .box {
                font-size: 14px;
                margin-bottom: 0.7rem;

                .title {
                    display: flex;
                    left: 0;

                    span {
                        color: red;
                        margin-right: 0.4rem;
                    }

                    b {
                        margin-bottom: 0.5rem;
                    }
                }

                .input {
                    border: 1.5px solid #e9eaeb;
                    padding: 0.3rem 1rem;
                }

                .description {
                    font-size: 12px;
                }

                //.popup-bg {
                //    background: rgba(0, 0, 0, 0.5);
                //    width: 100%;
                //    height: 100%;
                //    position: fixed;
                //    top: 0;
                //    left: 0;
                //    z-index: 6;
                //}

                //.btn {
                //    display: flex;
                //    justify-content: space-between;
                //}

                //.popup {
                //    position: absolute;
                //    bottom: 0;
                //    left: 0;
                //    z-index: 100;
                //    width: 100%;
                //    height: 400px;
                //    overflow: auto;
                //    border-top-left-radius: 8px;
                //    border-top-right-radius: 8px;
                //    background: #fff;
                //    text-align: left;
                //}

                //.cancle {
                //    color: #969799;
                //    padding: 15px 0 15px 18px;
                //    font-size: 14px;
                //}
                //
                //.confirm {
                //    padding: 15px 18px 15px 0;
                //    font-size: 14px;
                //}
            }

            .price {
                display: flex;

                .box {
                    flex: 1;
                }

                .box:nth-child(1) {
                    margin-right: 0.6rem;
                }

                .box:nth-child(2) {
                    margin-left: 0.6rem;
                }
            }
        }

        // 底部提交按钮
        .submit {
            font-size: 15px;
            display: flex;
            justify-content: space-between;
            margin-top: 2rem;

            .left {
                display: flex;
                justify-items: center;

                span {
                    color: #a2a3a4;
                    width: 11rem;
                    margin-left: 1rem;

                    a {
                        color: #f79100;
                    }
                }
            }

            .right {
                button {
                    background-color: #f79100;
                    color: #ffffff;
                    width: 4.6rem;
                    height: 2.53rem;
                    line-height: 2.53rem;
                    font-weight: 600;
                    text-align: center;
                    border-radius: 8px;
                    border: none;
                }
            }
        }
    }
}

</style>
